package com.informatics.polymer.server.substructureSearch;

import java.sql.SQLException;
import java.util.List;

import org.openscience.cdk.exception.CDKException;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.informatics.polymer.server.database.DatabaseInteraction;
/**
 * Substructure search restlet. Essentially given a substructure query it call the
 * derby database and returns all ids that are hits.
 * @author ed
 * @version 1.0
 */
public class SubstructureSearch extends Resource {
	public void init(Context context, Request request, Response response){
		super.init(context, request, response);
		getVariants().add(new Variant(MediaType.TEXT_PLAIN));
		id = (String) request.getAttributes().get("id");
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	private String id;

	// Respond to GET
	public Representation represent (Variant variant) throws ResourceException{
		Representation resource = null;
			if (!MediaType.TEXT_PLAIN.includes(variant.getMediaType())) {
				throw new ResourceException(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
			}
			else{
				StringBuffer sb = new StringBuffer();
			//	sb.append("P010001"+"\n");
			//	sb.append("P010002"+"\n");
				DatabaseInteraction databaseInteraction = new DatabaseInteraction();
				try {
					databaseInteraction.init();
					List<com.informatics.polymer.server.database.RepeatUnit> resu = databaseInteraction.getSelectedDBResults(id);
					for(com.informatics.polymer.server.database.RepeatUnit ru: resu){
						sb.append(ru.getId()+"\n");}
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 catch (CDKException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				resource = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); 
				return resource;
			}
	}

}
